package com.oa.android.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.oa.android.R;
import com.oa.android.adapter.FujAdapter;
import com.oa.android.entry.Fjian;
import com.oa.android.utils.ImageUtlis;
import com.oa.android.utils.UConstants;
import com.oa.android.utils.Util;
import com.oa.android.view.MyGridView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


/**
 * 添加邮件
 *
 * @author -zouqh
 */
public class AddGGaoActivity extends Activity implements OnClickListener {

    private ImageView close;
    private TextView title, send, sendTo, addfile, fuj;
    private EditText  emilTitle, emilContent;
    private List<File> listFile;
    private Dialog Jdialog;
    ProgressDialog dialog;
    private RadioGroup group;
    private RadioButton radioButton1,radioButton2;
    private String type="D";
    private String idStr;
    String personID="";
    private MyGridView listFj;
    private FujAdapter adapter;
    List<Fjian> list;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_ggao_activity);
//        type=Integer.parseInt(getIntent().getStringExtra("type"));
        close = (ImageView) findViewById(R.id.close);
        title = (TextView) findViewById(R.id.title_text);
        send = (TextView) findViewById(R.id.ritgh_text);
        sendTo = (TextView) findViewById(R.id.sendTo);
        emilTitle = (EditText) findViewById(R.id.emilTitle);
        addfile = (TextView) findViewById(R.id.addFile);
        fuj = (TextView) findViewById(R.id.fuj);
        emilContent = (EditText) findViewById(R.id.emilContent);
        group=(RadioGroup)findViewById(R.id.group);
        radioButton1=(RadioButton)findViewById(R.id.radio1);
        radioButton2=(RadioButton)findViewById(R.id.radio2);
        listFj=(MyGridView)findViewById(R.id.listFj);
        listFile = new ArrayList<>();
            send.setText("发布");
            title.setText("新增公告");
    getId();
        list=new ArrayList<>();
        adapter=new FujAdapter(AddGGaoActivity.this,list);
        listFj.setAdapter(adapter);
        send.setVisibility(View.VISIBLE);

        close.setOnClickListener(this);
        send.setOnClickListener(this);
//        sendTo.setOnClickListener(this);
        addfile.setOnClickListener(this);
        fuj.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (fuj.getText().length()>0){
                    pointDialog("确定清除附件吗？");
                }

                return false;
            }
        });
        listFj.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Log.e("listFj---",position+"---");
                list.remove(position);
                listFile.remove(position);
                adapter.notifyDataSetChanged();
                return false;
            }
        });
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.radio1:
                        type="D";
                        break;
                    case R.id.radio2:
                        type="B";
                        break;

                }
                System.out.println("AAAAAAAAAAAAAAAAAAA"+type);
            }
        });
        group.check(R.id.radio1);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        Intent intent;
        switch (v.getId()) {
            case R.id.close:
                finish();
                break;

            case R.id.ritgh_text:
//                String str1 = sendTo.getText().toString().trim();
                String str2 = emilTitle.getText().toString();
                String str3 = emilContent.getText().toString();
                 if (!Util.NoNull(str2)) {
                    Toast.makeText(getApplicationContext(), "公告主题不能为空！", Toast.LENGTH_SHORT).show();
                } else if (!Util.NoNull(str3)) {
                    Toast.makeText(getApplicationContext(), "公告内容不能为空！", Toast.LENGTH_SHORT).show();
                } else {
//                     addGgao(title,content,type,msg);
                     addGgao(str2,str3,type);


                }
                break;

            case R.id.addFile:
                intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, 1);
                break;
            case R.id.sendTo:
                startActivityForResult(new Intent(this,PersonActivity.class),2);
                break;

            default:
                break;
        }
    }

    private Uri mPhotoUri = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {//是否选择，没选择就不会继续

            if (requestCode==1){
                Uri uri = data.getData();
                String  path= ImageUtlis.getRealPathFromUri(this,uri);
                if (null==path||path.length()<=0){
                    Toast.makeText(this,"获取文件失败",Toast.LENGTH_SHORT).show();
                    return;
                }
                File file = new File(path);
                listFile.add(file);
                String s = fuj.getText().toString();
                if (s.length() > 0) {
                    fuj.setText(s + "|" + file.getName());
                } else {
                    fuj.setText(file.getName());
                }
                Fjian fjian=new Fjian();
                fjian.setOLDNAME(file.getName());
                list.add(fjian);
                adapter.notifyDataSetChanged();
                System.out.println("img_path===" +path);
            }else if (requestCode==2){
                if (data != null) {
                    String str = data.getStringExtra("person");
                    personID = data.getStringExtra("personID");
                    System.out.println("personID---"+personID);
                    sendTo.setText(str);
                }
            }

//
        }
    }




    /**
     * 提示
     */
    private void pointDialog(String str) {
        LayoutInflater inflaterDl = LayoutInflater.from(this);
        View layout = inflaterDl.inflate(R.layout.exti_dialog,
                null);
        // 对话框
        Jdialog = new Dialog(this);
        Jdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        Jdialog.show();

        Jdialog.setContentView(layout);
        TextView sure = (TextView) layout.findViewById(R.id.sureExti);
        TextView cancle = (TextView) layout.findViewById(R.id.cancleExti);
        TextView dialogTitle = (TextView) layout.findViewById(R.id.dialogTitle);
        dialogTitle.setText(str);
        sure.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
//				ContextUtil.getInstance().finishApp();
                Jdialog.cancel();
                fuj.setText("");
                listFile.clear();


            }
        });
        cancle.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Jdialog.dismiss();
            }
        });

    }


    //发布公告
    public void addGgao(String title, String content, String type) {
        if (null==dialog||!dialog.isShowing()){
            dialog = ProgressDialog.show(AddGGaoActivity.this, null, "发布中...", true, false);
        }

        Util.printLog("------------UConstants.ADD_GGAO-----", UConstants.ADD_GGAO);
        System.out.println("type-------------------"+type);
        RequestParams params = new RequestParams(UConstants.ADD_GGAO);
        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("EmpId", UConstants.EmpId);
        params.addBodyParameter("TITLE", title);
        params.addBodyParameter("CONTENT", content);
        params.addBodyParameter("ID", idStr);
//        params.addBodyParameter("FUJIAN", fuj.getText().toString());
        params.addBodyParameter("LX", type);

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getDownRoute------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        boolean success = object.getBoolean("success");
//                        String msg = object.getString("msg");
                        if (success) {
                            if (listFile.size()>0){
                                upFj();
                            }else{
                                isShow();
                                Toast.makeText(x.app(), "新增成功！", Toast.LENGTH_LONG).show();
                                GGaoActivity.gGaoActivity.setResh();
                                finish();
                            }

                        } else {
                            isShow();
                            Toast.makeText(x.app(), "新增失败！", Toast.LENGTH_LONG).show();
                        }
//
                    } catch (JSONException e) {
                        isShow();
                        e.printStackTrace();
                    }
                }else{
                    Toast.makeText(x.app(), "新增失败！", Toast.LENGTH_LONG).show();
                    isShow();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "新增出错！", Toast.LENGTH_LONG).show();
                isShow();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                isShow();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    //发布公告
    public void getId() {
        Util.printLog("------------UConstants.GET_ID-----", UConstants.GET_ID);
        dialog = ProgressDialog.show(this, null, "获取中...", true, false);
        RequestParams params = new RequestParams(UConstants.GET_ID);
//        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("TNAME", "ERPGGTZ");


        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getDownRoute------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        boolean success = object.getBoolean("success");
                        String msg = object.getString("msg");
                        if (success) {
                            idStr=msg;


                        } else {
                            isShow();
                            Toast.makeText(x.app(), "获取ID失败！", Toast.LENGTH_LONG).show();
                        }
//
                    } catch (JSONException e) {
                        isShow();
                        Toast.makeText(x.app(), "获取ID失败！", Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                }

                isShow();

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "新增出错！", Toast.LENGTH_LONG).show();
                isShow();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                isShow();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    //上传附件
    public void upFj() {

        RequestParams params = new RequestParams(UConstants.UP_FILI);
        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("TNAME", "ERPGGTZ");
        params.addBodyParameter("XH",idStr );
        Util.printLog("UConstants.UP_FILI------------onSuccess-----", UConstants.UP_FILI);
        for (int i=0;i<listFile.size();i++){
            params.addBodyParameter("FILE",listFile.get(i));
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getDownRoute------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        boolean success = object.getBoolean("success");

//                        String msg = object.getString("msg");
                        if (success) {
                            isShow();
                            Toast.makeText(x.app(),  "上传成功！", Toast.LENGTH_LONG).show();
                            GGaoActivity.gGaoActivity.setResh();
                            finish();
                        } else {
                            isShow();
                            Toast.makeText(x.app(), "附件上传失败！", Toast.LENGTH_LONG).show();
                        }
//
                    } catch (JSONException e) {
                        isShow();
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(),  "附件上传出错！", Toast.LENGTH_LONG).show();
                isShow();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                isShow();
            }

            @Override
            public void onFinished() {

            }
        });
    }


    private void isShow(){
        if (null!=dialog&&dialog.isShowing()){
            dialog.dismiss();
        }
    }


}
